package com.leyou.item.web;

import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("spec")
public class SpecController {

    private final SpecGroupService groupService;
    private final SpecParamService paramService;

    public SpecController(SpecGroupService groupService, SpecParamService paramService) {
        this.groupService = groupService;
        this.paramService = paramService;
    }

    /**
     * 测试，根据id 查询规格参数
     * @param id 规格参数id
     * @return 规格参数对象
     */
    @GetMapping("/param/{id}")
    public ResponseEntity<SpecParamDTO> querySpecParamById(@PathVariable("id") Long id) {
        return ResponseEntity.ok(new SpecParamDTO(paramService.getById(id)));
    }

    /**
     * 根据分类id查询规格组
     * @param id 分类id
     * @return 规格组集合
     */
    @GetMapping("/groups/of/category")
    public ResponseEntity<List<SpecGroupDTO>> querySpecGroupByCategory(@RequestParam("id") Long id){
        // SELECT * FROM tb_spec_group WHERE category_id = 105
        List<SpecGroup> list = groupService.query().eq("category_id", id).list();
        // 转换DTO
        List<SpecGroupDTO> dtoList = SpecGroupDTO.convertEntityList(list);
        // 返回
        return ResponseEntity.ok(dtoList);
    }

    /**
     * 根据条件查询规格参数
     * @param categoryId 商品分类id
     * @param groupId 规格组id
     * @param searching 是否参与搜索，true或者false
     * @return 符合条件的参数的集合
     */
    @GetMapping("/params")
    public ResponseEntity<List<SpecParamDTO>> queryParams(
            @RequestParam(value = "categoryId", required = false) Long categoryId,
            @RequestParam(value = "groupId", required = false) Long groupId,
            @RequestParam(value = "searching", required = false) Boolean searching
    ){
        List<SpecParamDTO> dtoList = paramService.queryParams(categoryId, groupId, searching);
        return ResponseEntity.ok(dtoList);
    }

    /**
     * 根据分类id查询规格组及规格组内的参数
     * @param id 分类id
     * @return 规格组及组内参数集合
     */
    @GetMapping("/list")
    public ResponseEntity<List<SpecGroupDTO>> querySpecs(@RequestParam("id") Long id){
        List<SpecGroupDTO> list = groupService.querySpecs(id);
        return ResponseEntity.ok(list);
    }
}
